// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/ex/string_ex.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_tv_widgets/config/kq_global.dart';
import 'package:kq_flutter_tv_widgets/resources/images.dart';
import 'package:kq_flutter_tv_widgets/widgets/divider/kq_divider.dart';
import 'package:kq_flutter_tv_widgets/widgets/image/kq_print_image.dart';
import 'package:kq_flutter_tv_widgets/widgets/overflowBox/kq_over_flow_box.dart';
import 'package:kq_flutter_tv_widgets/widgets/wrapFlow/kq_auto_column_flow.dart';

import '../../resources/kq_theme_colors.dart';

enum SimpleDividePosition {
  /// 头部
  top,

  /// 底部
  bottom
}

/// 只有标题，没有图片和副标题
class KqSimpleCard extends StatefulWidget {
  /// 卡片宽度
  final double? cardWidth;

  /// 卡片背景色:默认 KqThemeColors.bgDialog
  Color? backgroundColor;

  /// 选中状态，默认未选中
  bool? isSelect;

  /// 是否支持选择功能
  bool isCanSelect;

  /// 标题
  final String? title;

  /// 副标题
  final String? subTitle;

  /// 分隔线位置,未设置就不显示
  final SimpleDividePosition? dividePosition;

  /// 分隔线高度 默认：1.r
  final double? divideHeight;

  /// 底部widget,和bottomBtns实现一种
  final Widget? bottomBtnsView;

  /// 底部widget,和bottomBtnsView实现一种
  final List<Widget>? bottomBtns;

  /// tags 标签
  final List<Widget>? tags;

  /// 印章类型，使用[KqPrintType]
  final KqPrintType? printType;

  /// 卡片信息内容个数
  final int totalCount;

  /// 行数
  final int Function()? rowCountCallback;

  ///每行的列数
  final int Function(int row)? renderCrossAxisCountCallback;

  ///leftText
  final String Function(int row, int column)? renderLeftTextCallback;

  ///Text
  final String Function(int row, int column)? renderTextCallback;

  /// 指定位置的右边widget自定义
  final Widget? Function(int row, int column)? renderWidgetCallback;

  ///Text行数
  final int Function(int row, int column) renderTextMaxLineCallback;

  /// 点击
  final void Function()? onTap;

  /// 背景颜色回调
  final Color? Function()? renderBackgroundColorCallback;

  /// 进度条：当前进度值
  final double Function()? renderProgressValueCallback;

  /// 进度条：总的进度值
  final double Function()? renderTotalProgressValueCallback;

  /// 进度条：左边的widget
  final Widget Function()? renderProgressLeftWidgetCallback;

  /// 进度条：右边的widget
  final Widget Function()? renderProgressRightWidgetCallback;

  /// 进度条：右边的widget
  final Widget Function()? renderCustomTitleWidgetCallback;

  KqSimpleCard(
      {this.cardWidth,
      this.backgroundColor = KqThemeColors.bgDialog,
      this.isSelect = false,
      this.title,
      this.subTitle,
      this.dividePosition,
      this.divideHeight,
      this.bottomBtnsView,
      this.bottomBtns,
      this.tags,
      this.printType,
      this.onTap,
      this.isCanSelect = false,
      this.renderBackgroundColorCallback,
      this.renderLeftTextCallback,
      this.renderTextCallback,
      this.renderWidgetCallback,
      this.renderProgressValueCallback,
      this.renderTotalProgressValueCallback,
      this.renderProgressLeftWidgetCallback,
      this.renderProgressRightWidgetCallback,
      this.renderCustomTitleWidgetCallback,
      required this.totalCount,
      required this.renderCrossAxisCountCallback,
      required this.rowCountCallback,
      required this.renderTextMaxLineCallback,
      super.key});

  @override
  State<KqSimpleCard> createState() => _KqSimpleCardState();
}

class _KqSimpleCardState extends State<KqSimpleCard> {
  double widgetWidth = KqScreenUtil().screenWidth;

  /// 水平间距
  double spacing = 8.r;

  /// 垂直方向间距
  double runSpacing = 6.r;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      // color: KqThemeColors.bgDialog,
      width: widget.cardWidth ?? double.infinity,
      child: KqInkWell(
        onTap: () {
          widget.onTap?.call();
          setState(() {
            widget.backgroundColor =
                widget.renderBackgroundColorCallback?.call() ??
                    KqThemeColors.bgDialog;
          });
        },
        enableRipple: false,
        child: renderContent(),
      ),
    );
  }

  Widget renderContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        renderTopDividerWidget(),
        if (widget.isCanSelect)
          Container(
              color: widget.backgroundColor ?? KqThemeColors.bgDialog,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    renderSelectStatusWidget(),
                    Expanded(
                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: renderContentViewList())),
                  ])),
        if (!widget.isCanSelect)
          Container(
            color: widget.backgroundColor ?? KqThemeColors.bgDialog,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: renderContentViewList(),
            ),
          ),
      ],
    );
  }

  Widget renderSelectStatusWidget() {
    return SizedBox(
      width: 64.r,
      height: 140.r,
      child: Align(
        child: Image.asset(
          widget.isSelect != null && widget.isSelect!
              ? Images.commonIcCheckboxesSelectedEnabledSquare
              : Images.commonIcCheckboxesUnselectedEnabledSquare,
          width: 24.r,
          height: 24.r,
          package: KqGlobal.packageName,
        ),
      ),
    );
  }

  List<Widget> renderContentViewList() {
    return [
      SizedBox(
        height: 24.r,
      ),
      renderTitleInfo(),
      renderSubTitleInfo(),
      SizedBox(
        height: 16.r,
      ),
      renderProgressWidget(),
      renderWrapFlowWidget(),
      Visibility(
          visible: widget.bottomBtns != null || widget.bottomBtnsView != null,
          child: Padding(
            padding:
                EdgeInsets.symmetric(horizontal: widget.isCanSelect ? 0 : 24.r),
            child: const KqDivider(),
          )),
      Visibility(
          visible: widget.bottomBtns != null || widget.bottomBtnsView != null,
          child: renderBottomBtns()),
      Visibility(
          visible: widget.dividePosition != null &&
              widget.dividePosition == SimpleDividePosition.bottom,
          child: KqDivider(
            height: widget.divideHeight ?? 1.r,
          )),
    ].toList();
  }

  Widget renderTopDividerWidget() {
    return Visibility(
        visible: widget.dividePosition != null &&
            widget.dividePosition == SimpleDividePosition.top,
        child: KqDivider(
          height: widget.divideHeight ?? 12.r,
          color: KqThemeColors.bgTransparent,
        ));
  }

  List<Widget> renderTags() {
    List<Widget> tags = [];
    if (widget.tags != null) {
      for (var i = 0; i < widget.tags!.length; i++) {
        tags.add(widget.tags![i]);
        if (i != widget.tags!.length - 1) {
          tags.add(SizedBox(
            width: 6.r,
          ));
        }
      }
    }
    return tags;
  }

  Widget renderTitleInfo() {
    String title = widget.title ?? '';

    return Container(
      margin: EdgeInsets.only(left: widget.isCanSelect ? 0 : 24.r, right: 24.r),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
              child: widget.renderCustomTitleWidgetCallback != null
                  ? widget.renderCustomTitleWidgetCallback!()
                  : Text(title.ellipsis(),
                      style: TextStyle(
                          fontSize: 24.sp, color: KqThemeColors.textBlack85),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis)),
          Visibility(
              visible: widget.tags != null,
              child: Container(
                margin: EdgeInsets.only(top: 3.r),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: renderTags(),
                ),
              )),
        ],
      ),
    );
  }

  Widget renderSubTitleInfo() {
    if (widget.subTitle != null) {
      return Container(
        padding: EdgeInsets.only(left: widget.isCanSelect ? 0 : 24.r),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 12.r,
            ),
            Text(widget.subTitle!,
                style: TextStyle(
                    fontSize: 20.sp, color: KqThemeColors.textBlack65))
          ],
        ),
      );
    }
    return Container();
  }

  Widget renderProgressWidget() {
    if (widget.renderProgressValueCallback != null &&
        widget.renderTotalProgressValueCallback != null) {
      double? currentProgress = widget.renderProgressValueCallback!();
      double? totalProgress = widget.renderTotalProgressValueCallback!();
      Widget? leftWidget = widget.renderProgressLeftWidgetCallback?.call();
      Widget? rightWidget = widget.renderProgressRightWidgetCallback?.call();
      return Container(
          padding: EdgeInsets.only(
              left: widget.isCanSelect ? 0 : 24.r, right: 24.r, bottom: 16.r),
          child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                if (leftWidget != null) leftWidget,
                if (leftWidget != null)
                  SizedBox(
                    width: 16.r,
                  ),
                Expanded(
                    child: LinearProgressIndicator(
                  value:
                      totalProgress == 0 ? 0 : currentProgress / totalProgress,
                  color: KqThemeColors.textWork,
                  backgroundColor: KqThemeColors.radioUnCheckBorderColor,
                  minHeight: 10.r,
                  borderRadius: BorderRadius.all(Radius.circular(10.r)),
                )),
                if (rightWidget != null)
                  SizedBox(
                    width: 16.r,
                  ),
                if (rightWidget != null) rightWidget,
              ]));
    }
    return Container();
  }

  Widget renderWrapFlowWidget() {
    return Container(
      margin: EdgeInsets.only(bottom: 24.r),
      padding:
          EdgeInsets.only(right: 24.r, left: widget.isCanSelect ? 0 : 24.r),
      child: renderWrapFlowContent(),
    );
  }

  Widget renderWrapFlowContent() {
    if (widget.printType != null) {
      return KqOverFlowBox(
          referenceWidget: KqAutoColumnFlow(
              spacing: spacing,
              runSpacing: runSpacing,
              fontSize: 20.sp,
              iconWidth: 200.r,
              leftTextFontSize: 20.sp,
              viewType: 3,
              totalCount: widget.totalCount,
              backgroundColor: widget.backgroundColor ?? KqThemeColors.bgDialog,
              renderCrossAxisCountCallback: widget.renderCrossAxisCountCallback,
              renderLeftTextCallback: widget.renderLeftTextCallback,
              renderTextCallback: widget.renderTextCallback,
              rowCountCallback: widget.rowCountCallback,
              renderWidgetCallback: widget.renderWidgetCallback,
              renderTextMaxLineCallback: widget.renderTextMaxLineCallback),
          overflowBoxWidget: KqPrintImage(printType: widget.printType!),
          visible: true,
          position: BoxToReferencePosition.bottom,
          alignment: Alignment.bottomRight,
          maxWidth: 64.r,
          maxHeight: 64.r);
    }
    return KqAutoColumnFlow(
        spacing: spacing,
        runSpacing: runSpacing,
        fontSize: 20.sp,
        iconWidth: 200.r,
        leftTextFontSize: 20.sp,
        viewType: 3,
        totalCount: widget.totalCount,
        backgroundColor: widget.backgroundColor ?? KqThemeColors.bgDialog,
        renderCrossAxisCountCallback: widget.renderCrossAxisCountCallback,
        renderLeftTextCallback: widget.renderLeftTextCallback,
        renderTextCallback: widget.renderTextCallback,
        rowCountCallback: widget.rowCountCallback,
        renderWidgetCallback: widget.renderWidgetCallback,
        renderTextMaxLineCallback: widget.renderTextMaxLineCallback);
  }

  Widget renderBottomBtns() {
    if (widget.bottomBtnsView != null) {
      return Container(
        padding:
            EdgeInsets.symmetric(horizontal: widget.isCanSelect ? 0 : 24.r),
        child: widget.bottomBtnsView,
      );
    } else if (widget.bottomBtns != null) {
      List<Widget> btns = [];
      for (var i = 0; i < widget.bottomBtns!.length; i++) {
        btns.add(widget.bottomBtns![i]);
        if (widget.bottomBtns!.length - 1 != i) {
          btns.add(SizedBox(
            width: 8.r,
          ));
        }
      }
      return Container(
        // height: 48.r,
        padding: EdgeInsets.symmetric(horizontal: 16.r, vertical: 8.r),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: btns,
        ),
      );
    }
    return Container();
  }
}
